﻿@model PaymentInfoModel

<script src="@CyberSourceDefaults.FlexMicroformScriptUrl" asp-exclude-from-bundle="true" asp-location="Footer"></script>

<style>
    .inputs * {
        width: auto !important;
        min-width: 150px;
    }

    .expire-container {
        line-height: 40px;
        font-size: 18px;
    }

    .flex-microform-pay-btn {
        margin-top: 30px;
    }
</style>

@if (Model.ShowExistingTokenSection)
{
    <style>
        #pnlNewCard {
            display: none;
        }

        .flex-microform-pay-btn {
            display: none;
        }
    </style>

    <div class="form-fields">
        <div class="inputs" id="pnlNewOrExistingCard">
            <label asp-for="NewCard" asp-postfix=":"></label>
            <input asp-for="NewCard" />
            <span asp-validation-for="NewCard"></span>
        </div>

        <div id="pnlExistingToken">
            @foreach (var card in Model.ExistingTokens)
            {
                <div class="inputs">
                    <label for="existingcard_@Model.ExistingTokens.IndexOf(card)">@card.Text</label>
                    <input class="existing-token" id="existingcard_@Model.ExistingTokens.IndexOf(card)" type="radio" name="SelectedTokenId" value="@(card.Value)" checked="@card.Selected" />
                </div>
            }
            <span asp-validation-for="SelectedTokenId"></span>
        </div>
    </div>

    <script asp-location="Footer">
        $(document).ready(function () {
            toggleNewAndExistingCardSection();
        });

        $('#NewCard').change(function () {
            toggleNewAndExistingCardSection();
        });

        function toggleNewAndExistingCardSection() {
            if ($('#NewCard').prop('checked')) {
                $('#pnlNewCard').show();
                $('#pnlExistingToken').hide();
            } else {
                $('#pnlNewCard').hide();
                $('#pnlExistingToken').show();
            }
        }
    </script>
}
else
{
    <input type="hidden" asp-for="NewCard" />
}

<div class="form-fields" id="pnlNewCard">
    @if (Model.IsFlexMicroFormEnabled)
    {
        <style>
            .flex-microform {
                background: #ffffff;
                -webkit-transition: background 200ms;
                transition: background 200ms;
                height: 36px;
                width: 320px !important;
                border: 1px solid #ddd;
                padding: 8px;
                vertical-align: middle;
            }

            .flex-microform-input {
                display: inline-block;
            }
        </style>

        <input type="hidden" asp-for="TransientToken" />

        <script asp-location="Footer">
            $(document).ready(function () {
                $('.payment-info-next-step-button').hide();

                var payButton = $('#pay-button');
                var transientToken = $('#TransientToken');
                var expMonth = $('#ExpireMonth');
                var expYear = $('#ExpireYear');
                var captureContext = '@Model.CaptureContext';

                var myStyles = {}; // custom styles that will be applied to each field we create using Microform
                var flex = new Flex(captureContext);
                var microform = flex.microform({
                    styles: myStyles
                });
                var number = microform.createField('number', {
                    placeholder: ''
                });
                var securityCode = microform.createField('securityCode', {
                    placeholder: ''
                });
                number.load('#number-container');
                securityCode.load('#securityCode-container');

                payButton.click(function () {
                    displayAjaxLoading(true)

                    var newCardSelected = $('#NewCard').prop('checked');
                    var isNewCard = @((!Model.ShowExistingTokenSection).ToString().ToLower());
                    var payerAuthenticationEnabled = @(settings.PayerAuthenticationEnabled.ToString().ToLower());

                    if (newCardSelected || isNewCard) {
                        var options = {
                            expirationMonth: expMonth.val().toString().padStart(2, '0'),
                            expirationYear: expYear.val()
                        };
                        microform.createToken(options, function (err, token) {
                            if (err) {
                                var message = err.message + " ";
                                if (err.details) {
                                    $.each(err.details, function (key, value) {
                                        if (value.message) {
                                            message += value.message;
                                            message += "; ";
                                        }
                                    });
                                }
                                displayAjaxLoading(false);
                                displayBarNotification(message, 'error', 3500);
                            } else {
                                if (token == null || token == "" || typeof (token) == 'undefined') {
                                    displayAjaxLoading(false);
                                    alert('Failed to pay');
                                } else {
                                    transientToken.val(JSON.stringify(token));
                                    var tokenPayload = parseJwt(token);
                                    if (!payerAuthenticationEnabled) {
                                        displayAjaxLoading(false);
                                        $('.payment-info-next-step-button').click();
                                    } else {
                                        setupPayerAuth(tokenPayload.jti);
                                    }
                                }
                            }
                        });
                    } else {
                        if (!payerAuthenticationEnabled) {
                            displayAjaxLoading(false);
                            $('.payment-info-next-step-button').click();
                        } else {
                            setupPayerAuth();
                        }
                    }
                });

                $('#step-up-iframe').on('load', function () {
                    try {
                        var frameLocation = this.contentWindow?.location?.href
                        if (frameLocation == '@Url.RouteUrl(CyberSourceDefaults.PayerRedirectRouteName, null, webHelper.GetCurrentRequestProtocol())') {
                            $('#step-up-modal').modal('hide');
                            $('body').removeClass('modal-open');
                            $('.modal-backdrop').remove();
                            validatePayerAuth();
                        }
                    } catch {
                        // catch cross-origin error when trying to read iframe location
                    }
                });
            });

            function parseJwt(token) {
                var base64Url = token.split('.')[1];
                var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
                var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
                    return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                }).join(''));
                return JSON.parse(jsonPayload);
            }

            function setupPayerAuth(token) {
                $('#ReferenceId').val('');
                $('#AuthenticationTransactionId').val('');
                if (!token) {
                    var customerToken = $('.existing-token:checked').val();
                }
                var postData = {
                    customerTokenId: customerToken,
                    transientToken: token
                };
                addAntiForgeryToken(postData);
                $.ajax({
                    cache: false,
                    type: 'POST',
                    url: '@(Url.Action("Setup", "CyberSourcePayerAuthentication"))',
                    data: postData,
                    success: function (data, textStatus, jqXHR) {
                        if (typeof (data) != 'undefined' && data != null && data.success) {
                            $('#ReferenceId').val(data.referenceId);
                            var cardinalCollectionForm = $('#cardinal-collection-form');
                            if (cardinalCollectionForm) {
                                cardinalCollectionForm.attr('action', data.deviceDataCollectionUrl);
                                $('#cardinal-collection-form-input').val(data.accessToken);
                                cardinalCollectionForm.submit();
                                setTimeout(function () {
                                    enrollPayerAuth(token);
                                }, 2000);
                            }
                        }
                        else {
                            displayAjaxLoading(false);
                            displayBarNotification(data.message, 'error', 3500);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        displayAjaxLoading(false);
                        displayBarNotification('Failed to setup payer authentication.', 'error', 3500);
                    }
                });
            }

            function enrollPayerAuth(token) {
                if (!token) {
                    var customerToken = $('.existing-token:checked').val();
                }
                var postData = {
                    referenceId: $('#ReferenceId').val(),
                    customerTokenId: customerToken,
                    transientToken: token
                };
                addAntiForgeryToken(postData);
                $.ajax({
                    cache: false,
                    data: postData,
                    type: 'POST',
                    url: '@(Url.Action("Enrollment", "CyberSourcePayerAuthentication"))',
                    success: function (data, textStatus, jqXHR) {
                        if (typeof (data) != 'undefined' && data != null && data.success) {
                            $('#AuthenticationTransactionId').val(data.authenticationTransactionId);
                            displayAjaxLoading(false);
                            if (data.complete) {
                                validatePayerAuth();
                            }
                            else {
                                var stepUpForm = $('#step-up-form');
                                if (stepUpForm) {
                                    stepUpForm.attr('action', data.stepUpUrl);
                                    $('#step-up-form-input').val(data.accessToken);
                                    $('#step-up-modal').modal({
                                        backdrop: 'static',
                                        keyboard: false
                                    });
                                    stepUpForm.submit();
                                }
                            }
                        }
                        else {
                            displayAjaxLoading(false);
                            displayBarNotification(data.message, 'error', 3500);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        displayAjaxLoading(false);
                        displayBarNotification('Failed to check payer authentication enrollment', 'error', 3500);
                    }
                });
            }

            function validatePayerAuth() {
                displayAjaxLoading(true);
                var postData = {
                    authenticationTransactionId: $('#AuthenticationTransactionId').val()
                };
                addAntiForgeryToken(postData);
                $.ajax({
                    cache: false,
                    data: postData,
                    type: 'POST',
                    url: '@(Url.Action("Validate", "CyberSourcePayerAuthentication"))',
                    success: function (data, textStatus, jqXHR) {
                        if (typeof (data) != 'undefined' && data != null && data.success) {
                            displayAjaxLoading(false);
                            $('.payment-info-next-step-button').click();
                        }
                        else {
                            displayAjaxLoading(false);
                            displayBarNotification(data.message, 'error', 3500);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        displayAjaxLoading(false);
                        displayBarNotification('Failed to validate payer authentication', 'error', 3500);
                    }
                });
            }
        </script>
    }
    <div class="inputs">
        <label asp-for="CardNumber">@T("Payment.CardNumber"):</label>
        @if (!Model.IsFlexMicroFormEnabled)
        {
            <input type="text" asp-for="CardNumber" style="width:165px;" autocomplete="off" maxlength="22" />
            <span asp-validation-for="CardNumber"></span>
        }
        else
        {
            <div class="flex-microform-input">
                <div id="number-container"></div>
            </div>
        }
    </div>
    <div class="inputs">
        <label asp-for="CardNumber">@T("Payment.CardNumber"):</label>
        <span class="expire-container">
            <select asp-for="ExpireMonth" asp-items="Model.ExpireMonths"></select>
            <span>/</span>
            <select asp-for="ExpireYear" asp-items="Model.ExpireYears"></select>
        </span>
    </div>
    <div class="inputs">
        <label asp-for="Cvv">@T("Payment.CardCode"):</label>
        @if (!Model.IsFlexMicroFormEnabled)
        {
            <input type="text" asp-for="Cvv" style="width:60px;" autocomplete="off" maxlength="4" />
            <span asp-validation-for="Cvv"></span>
        }
        else
        {
            <div class="flex-microform-input">
                <div id="securityCode-container"></div>
            </div>
        }
    </div>
    @if (Model.TokenizationEnabled)
    {
        <div class="inputs">
            <label asp-for="SaveCardOnFile" asp-postfix=":"></label>
            <input asp-for="SaveCardOnFile" />
            <span asp-validation-for="SaveCardOnFile"></span>
        </div>
    }
</div>

@if (Model.IsFlexMicroFormEnabled)
{
    <div class="buttons">
        <button type="button" class="button-1 flex-microform-pay-btn" id="pay-button">@T("Plugins.Payments.CyberSource.Payment.PayNow")</button>
    </div>
}

@if (settings.PayerAuthenticationEnabled)
{
    <input type="hidden" id="ReferenceId" name="ReferenceId" />
    <input type="hidden" id="AuthenticationTransactionId" name="AuthenticationTransactionId" />
}

@if (orderSettings.OnePageCheckoutEnabled)
{
    @NopHtml.GenerateInlineScripts(ResourceLocation.Footer)
}